package noema.serviceTask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;

@Stateless
public class ServiceTaskHandler implements WorkItemHandler {

	@Resource(mappedName = "java:/XAConnectionFactory")
	private ConnectionFactory connFactory;
	@Resource(mappedName = "topic/analysisService")
	private Topic dest;
	
	@Override
	public void abortWorkItem(WorkItem i, WorkItemManager m) {
		m.abortWorkItem(i.getId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public void executeWorkItem(WorkItem i, WorkItemManager m) {
		Map<String, Object> params=i.getParameters();
		if(params.keySet().size()!=1){
			throw new IllegalArgumentException("Service Task only support one parameter (List<String>)");
		}
		
		List<String> analysis;
		try{
			analysis = (List<String>)params.get(params.keySet().iterator().next());
		}catch(Exception e){
			throw new IllegalArgumentException("Service Task only support one parameter (List<String>)");
		}
		
		try {
			Connection jmsConn = connFactory.createConnection();
			Session jmsSession = jmsConn.createSession(true,
					Session.AUTO_ACKNOWLEDGE);
			MessageProducer jmsProducer = jmsSession.createProducer(dest);
			MapMessage jmsMess = jmsSession.createMapMessage();
			for(String s:analysis){
				jmsMess.setString(s, s);
			}
			jmsMess.setLong("processInstanceId", i.getProcessInstanceId());
			jmsProducer.send(jmsMess);
			jmsSession.commit();
			jmsSession.close();
			jmsConn.close();
		} catch (JMSException e) {
			e.printStackTrace();
			m.abortWorkItem(i.getId());
		}
		m.completeWorkItem(i.getId(), new HashMap<String, Object>());
	}

}
